﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Lk.Common.Extenstion;
using Lk.IServices;
using Lk.Web.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;

namespace Lk.Web.Controllers
{
    public class AccountController : Controller
    {
        private IUserService userService;


        public AccountController(IUserService userService)
        {
            this.userService = userService;
        }
        public IActionResult Login(string returnUrl = null)
        {
            ViewBag.returnUrl = returnUrl;
            return View();
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model)
        {
            try
            {
                //模型验证通过后
                if (ModelState.IsValid)
                {
                    var user = await userService.GetByName(model.UserName);
                    model.Password = (model.Password).EncryptText(user.create_time.ToString());
                    //验证用户名密码
                    if (user != null && string.Equals(model.Password, user.pass_word))
                    {
                        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);//一定要声明AuthenticationScheme
                        identity.AddClaim(new Claim(ClaimTypes.Name, user.user_name));
                        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.id.ToString()));

                        await HttpContext.SignInAsync(identity.AuthenticationType,
                                                      new ClaimsPrincipal(identity),
                                                      new AuthenticationProperties
                                                      {
                                                          IsPersistent = true,
                                                          RedirectUri = "/Home/Index",
                                                          ExpiresUtc = new System.DateTimeOffset(dateTime: DateTime.Now.AddHours(6)),
                                                      });
                        //更新登陆时间
                        user.update_time = DateTime.Now;
                        await userService.Update(user);

                        return Redirect("home");
                    }
                    else
                    {
                        await HttpContext.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                        ModelState.AddModelError("", "用户名或密码错误！");
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "用户名或密码错误！");
            }
            return View(model);
        }


        public async Task<ActionResult> Register()
        {

            var dt = DateTime.Now;
            await userService.Add(new Model.Models.users()
            {
                create_time = dt,
                user_name = "test",
                pass_word = "12345".EncryptText(dt.ToString()),
                head_img_url = "1",
                applet_open_id = "121",
                last_read_video_id = new Guid(),
                open_id = "11",
                nick_name = "test",
                state = true,
                unionid = "112",
                update_time = DateTime.Now,
                total_score = 0,
                shoping_applet_open_id = "111", id=Guid.NewGuid()
            });
            return View();
        }
    }
}